package cn.example.practice.servlet;


import cn.example.practice.db.ShopCartDao;
import cn.example.practice.model.CartItem;
import cn.example.practice.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.List;

@WebServlet(name = "ToCheckoutServlet", urlPatterns = "/toCheckoutServlet")
public class ToCheckoutServlet extends HttpServlet {
    private final ShopCartDao shopCartDao = new ShopCartDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        // 检查用户是否登录
//        if (loginUser == null) {
//            // 保存当前URL到session，登录后可以跳转回来
//            session.setAttribute("returnUrl", request.getRequestURI());
//            response.sendRedirect(request.getContextPath() + "/toLoginServlet");
//            return;
//        }

        // 获取用户的购物车商品
        List<CartItem> cartItems = shopCartDao.getCartItems(loginUser.getId());

        // 检查购物车是否为空
        if (cartItems == null || cartItems.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/shopListServlet");
            return;
        }

        // 计算总金额
        float total = 0;
        for (CartItem item : cartItems) {
            total += item.getPrice() * item.getQuantity();
        }

        // 设置请求属性
        request.setAttribute("cartItems", cartItems);
        request.setAttribute("total", total);

        // 转发到结算页面
        request.getRequestDispatcher("/WEB-INF/jsp/checkout.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
